//
//  OAuthUIViewController.swift
//  JHSinaWeibo
//
//  Created by apple on 16/5/27.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthUIViewController: UIViewController {
    //声明webView属性
    let webView = UIWebView()
    
        override func loadView() {
        //在loadView阶段把根视图换成webView
        view = webView
    //设置代理
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavBar()
      loadOauthPage()
    }
    //打开授权页面
   private func loadOauthPage(){
    //获取request对象
    let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id+"&redirect_uri="+redirect_uri
    let url = NSURL(string:urlString)!
    let request = NSURLRequest(URL: url)
     webView.loadRequest(request)
  }
}
//设置导航条 监听按钮的点击事件
extension OAuthUIViewController{
    
    //按钮的点击事件
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func testAccount() {
        //使用webView 执行js 字符串
        //js 动态注入
        let jsString = "document.getElementById('userId').value = '15600908541', document.getElementById('passwd').value = 'hjh19930528' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    //完成导航条的设置
    private func setNavBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem( title: "关闭", target: self, action: #selector(OAuthUIViewController.close))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账户",target: self,action: #selector(OAuthUIViewController.testAccount))
    }

}
//使用进度条显示加载进度

extension OAuthUIViewController:UIWebViewDelegate{
   //显示用户等待指示器
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //隐藏用户等待指示器
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //授权成功后就会 回调心得页面 在回调页面的地址中就会获得授权码
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
    //打印url  absoluteString是绝对路径
        let urlString = request.URL?.absoluteString ?? ""
        //定义授权成功的标记
        let successFlag = "code="
        //print(url)
        //截取获取成功饿字符串中的code
        if urlString.containsString(successFlag) {
        //授权成功
            //
            let range = urlString.rangeOfString(successFlag)!
           let code = urlString.substringFromIndex(range.endIndex)
            print(code,urlString)
            //获取授权码之后，应该使用code码 请求token（用户登录口令）
            JHUserAccountModel.sharedAccountViewModel.loadAccessToken(code, finished: { (isSuccess) in
                if !isSuccess{
                
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                    return
                }
                //成功
                UIApplication.sharedApplication().keyWindow?.rootViewController = JHWelcomeViewController()
                
                 NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: nil)
            })
            
           
            //不加载网页
            return false
        }
        return true
    }
//    //使用code 加载用户授权的token（登录令牌）
//    private func loadAccessToken(code:String){
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        let parameters = ["client_id" :client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
//        
//        JHNetWorkTools.sharedTool.request(.POST, urlString: urlString, parameters: parameters){(responseObject,error) in
//           print(responseObject,error)
////            请求token成功之后 使用token和uid获取用户信息
//            if error != nil {
//            SVProgressHUD.showErrorWithStatus("亲爱的没有网啦")
//            return
//            }
//            //请求成功
//            self.loadUserInfo(responseObject)
//        }
//    }
//    //请求用户信息
//    private func loadUserInfo(response:AnyObject?) {
//      guard  let result = response as? [String : AnyObject] else {
//        SVProgressHUD.showErrorWithStatus("亲爱的没有网啦")
//            return
//        }
//        let token = result["access_token"]!
//        let uid = result["uid"]!
//        
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        
//        let parameters = ["access_token":token,"uid":uid]
//        JHNetWorkTools.sharedTool.request(.GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
//            if error != nil {
//            SVProgressHUD.showErrorWithStatus("亲爱的没有网啦")
//                return
//            }
//            //请求成功
//         guard var dict = responseObject as? [String :AnyObject] else{
//            SVProgressHUD.showErrorWithStatus("亲爱的没有网啦")
//                return
//            }
////            用户信息应该保存用户信息到本地
//            //合并两个字典，统一保存用户数据到本地
//            
//            for (key,value) in result {
//            dict[key] = value
//            }
//
//            //1.将dict转换为模型对象
//            let user = JHUserAccount(dict:dict)
//            //2.将模型对象转换为字典
//            let keys = ["access_token","expires_in","uid","name","avatar_large"]
//      let userInfo = user.dictionaryWithValuesForKeys(keys)
//            print("userInfo")
//            //3.获取字典数据
//            //使用偏好设置 保存字典数据
//                        let userDefaults = NSUserDefaults.standardUserDefaults()
//                        //不能够向偏好设置中保存nil
//                        userDefaults.setObject(userInfo, forKey: userInfoKey)
//            //同步
//            userDefaults.synchronize()
//            print(NSHomeDirectory())
//                    }
//    
//    }
}